<?php

class Email {
    const FROM = 'notify@ecustxytx.com';
    const PASS = 'YNSp9IZ8Gs47';
    const SERVER = 'smtp.exmail.qq.com';
    const PORT = '25';
    protected static $hackerGroup = [
        'admin@qiujiahui.com',
        '120945561@qq.com',
        '615877848@qq.com'
    ];
    public static $reportGroup = [
        '李佳' => 'dawn_lj@163.com',
        '明誉' => '732731552@qq.com',
        '万可鑫' => '15216790089@163.com',
        '邱家辉' => 'admin@qiujiahui.com',
        '刘旭利' => 'ecust_lxl@126.com',
    ];

    public static function report($subject, $body, $group = 'hacker') {
        if ($group == 'hacker') {
            foreach (self::$hackerGroup as $hacker) self::send($hacker, $subject, $body);
        } elseif ($group == 'report') {
            foreach (self::$reportGroup as $hacker) self::send($hacker, $subject, $body);
        } else {
            throw new Exception('Email group not found!');
        }
    }

    public static function send($to, $subject, $body) {
        $q = new Queue('EmailSender');
        $q->push(compact('to', 'subject', 'body'));
    }

    public static function direct_send($to, $subject, $body) {
        //标题不能带换行
        $subject = str_replace("\r\n", ' ', $subject);
        //行首的“.”是SMTP预留的格式，需要用“..”转意
        $body = preg_replace('/(=?^|\r\n)\./', '..', $body);

        $s = fsockopen(self::SERVER, self::PORT);
        fgets($s);
        //构造邮件内容数据
        $data = array(
          'MIME-Version: 1.0',
          'Content-Type: text/html; charset=utf-8',
          'From: ' . self::FROM,
          'To: ' . $to,
          'Subject: ' . $subject,
          "\r\n$body",
          '.'
        );
        $username = base64_encode(self::FROM);
        //根据SMTP协议与邮件服务器做一些应答
        foreach (array(
                   'HELO WEBMASTER',
                   'AUTH LOGIN',
                   $username,
                   base64_encode(self::PASS),
                   'MAIL FROM: <' . self::FROM . '>',
                   'RCPT TO: <' . $to . '>',
                   'DATA', implode("\r\n", $data)
                 ) as $i) {
          //发送消息
          fwrite($s, "$i\r\n");
          //等待返回并获取返回信息
          $m = fgets($s);
          //如果返回的是错误信息则结束函数
          if ($m[0] > 3) return $m;
        }
        //关闭sock
        fclose($s);
    }
}